// PointLightedCube_perFragment.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
  `attribute vec4 a_position;
  attribute vec4 a_normal;
  attribute vec2 a_TexCoord;
  uniform vec3 u_lightWorldPosition;  // 光源位置
  uniform mat4 u_world;    // Model matrix
  uniform mat4 u_worldViewProjection;
  uniform mat4 u_worldInverseTranspose;   // Transformation matrix of the normal
  varying vec3 v_normal;
  varying vec3 v_surfaceToLight;
  varying vec3 v_surfaceToView;
  varying vec2 v_TexCoord;
  
  void main() {
    // 将位置和矩阵相乘
    gl_Position = u_worldViewProjection * a_position;

    // 重定向法向量并传递到片断着色器
    v_normal = normalize(vec3(u_worldInverseTranspose * a_normal));

    // 计算表面的世界坐标
    vec3 surfaceWorldPosition = vec3(u_world * a_position);

    // 计算表面到光源的方向
    // 然后传递到片断着色器
    v_surfaceToLight = u_lightWorldPosition - surfaceWorldPosition;

    v_TexCoord = a_TexCoord;
  }`;

// Fragment shader program
var FSHADER_SOURCE =
  `#ifdef GL_ES
  precision mediump float;
  #endif
  varying vec3 v_normal;
  varying vec3 v_surfaceToLight;
  varying vec2 v_TexCoord;
  uniform sampler2D u_Sampler;
  uniform float u_shininess;
  uniform vec3 u_specularColor;
  uniform vec3 u_lightColor;
  uniform vec3 u_AmbientLight;
  uniform vec3 u_lightDirection;
  uniform float u_innerLimit;     // 在点乘空间中
  uniform float u_outerLimit;     // 在点乘空间中

  void main() {
    // 由于 v_normal 是可变量，所以经过插值后不再是单位向量，
    // 单位化后会成为单位向量
    vec3 normal = normalize(v_normal);
   
    vec3 surfaceToLightDirection = normalize(v_surfaceToLight);
   
    vec3 halfVector = normalize(surfaceToLightDirection);

    float light = 0.0;
    float specular = 0.0;
    float dotFromDirection = dot(surfaceToLightDirection, -u_lightDirection);

    float limitRange = u_innerLimit - u_outerLimit;

    float inLight = clamp((dotFromDirection - u_outerLimit) / limitRange, 0.0, 1.0);
    light = inLight * dot(normal, surfaceToLightDirection);
    specular = inLight * pow(dot(normal, halfVector), u_shininess);

    gl_FragColor = texture2D(u_Sampler, v_TexCoord);

    // 设置环境光
    vec3 diffuse = u_lightColor * gl_FragColor.rgb * light;
    vec3 ambient = u_AmbientLight * gl_FragColor.rgb;
    gl_FragColor.rgba = vec4(diffuse + ambient, gl_FragColor.a);
    
    // 直接加上高光
    gl_FragColor.rgb += specular;
  }`;

  var VSHADER_SOURCE_LIGHT =
  `attribute vec4 a_Position;
  uniform mat4 u_MvpMatrix;
  void main() {
    gl_Position = u_MvpMatrix * a_Position;
  }`;

// 片元着色器程序
var FSHADER_SOURCE_LIGHT =
`precision mediump float;
void main() {
  gl_FragColor = vec4(1, 0, 0 ,1);
}`;

var VSHADER_SOURCE_LAND =
`attribute vec4 a_Position;
uniform mat4 u_MvpMatrix;
attribute vec2 a_TexCoord;
varying vec2 v_TexCoord;
void main() {
  gl_Position = u_MvpMatrix * a_Position;
  v_TexCoord = a_TexCoord;
}`;

// 片元着色器程序
var FSHADER_SOURCE_LAND =
`precision mediump float;
uniform sampler2D u_Sampler;
varying vec2 v_TexCoord;
void main() {
  gl_FragColor = texture2D(u_Sampler, v_TexCoord);
}`;

var program;
var lightProgram;
var landProgram;
var image = new Image();
function main() {
  image.onload = function () {
      draw();
  };
  image.src = "../resources/img.png";
}

function draw() {
  // Retrieve <canvas> element
  var canvas = document.getElementById('webgl');

  // Get the rendering context for WebGL
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  if (!initShaders(gl, VSHADER_SOURCE_LIGHT, FSHADER_SOURCE_LIGHT)) {
    console.log("Failed to intialize shaders.");
    return;
  }
  lightProgram = gl.program;

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE_LAND, FSHADER_SOURCE_LAND)) {
    console.log("Failed to intialize shaders.");
    return;
  }
  landProgram = gl.program;

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }
  program = gl.program;
  gl.useProgram(program)
  
  // Set the clear color and enable the depth test
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);

  // Get the storage locations of uniform variables
  var u_world = gl.getUniformLocation(gl.program, 'u_world');
  var u_worldViewProjection = gl.getUniformLocation(gl.program, 'u_worldViewProjection');
  var u_worldInverseTranspose = gl.getUniformLocation(gl.program, 'u_worldInverseTranspose');
  var u_lightWorldPosition = gl.getUniformLocation(gl.program, 'u_lightWorldPosition');
  var lightColor = gl.getUniformLocation(gl.program, "u_lightColor");
  var specularColorLocation = gl.getUniformLocation(gl.program, "u_specularColor");
  var shininessLocation = gl.getUniformLocation(gl.program, "u_shininess");
  var u_AmbientLight = gl.getUniformLocation(gl.program, 'u_AmbientLight');
  var lightDirectionLocation = gl.getUniformLocation(gl.program, "u_lightDirection");

  var u_innerLimit = gl.getUniformLocation(gl.program, "u_innerLimit");
  var u_outerLimit = gl.getUniformLocation(gl.program, "u_outerLimit");

  if (!u_world || !u_worldViewProjection || !u_worldInverseTranspose  || !u_lightWorldPosition) { 
    console.log('Failed to get the storage location');
    return;
  }

  var lightDirection = [0, -1.0, 0];
  var lightX = 0;
  var lightY = 5.0;
  var lightZ = 0;
  var eyeX = 1.0;
  var eyeY = 8.0;
  var eyeZ = 8.0;
  var innerLimit = degToRad(10);
  var outerLimit = degToRad(15);
  var cameraAngleRadians = degToRad(0);
  var shiness = 180;
  // Setup a ui.
  webglLessonsUI.setupSlider("#rotation", {value: (cameraAngleRadians), slide: updateRotation, min: -360, max: 360});
  webglLessonsUI.setupSlider("#lightX", {value: lightX, slide: updatelightX, min: -2, max: 10, precision: 2, step: 0.001});
  webglLessonsUI.setupSlider("#lightY", {value: lightY, slide: updatelightY, min: -2, max: 10, precision: 2, step: 0.001});
  webglLessonsUI.setupSlider("#lightZ", {value: lightZ, slide: updatelightZ, min: -2, max: 10, precision: 2, step: 0.001});
  webglLessonsUI.setupSlider("#eyeX", {value: eyeX, slide: updateEyeX, min: -10, max: 20});
  webglLessonsUI.setupSlider("#eyeY", {value: eyeY, slide: updateEyeY, min: -10, max: 20});
  webglLessonsUI.setupSlider("#eyeZ", {value: eyeZ, slide: updateEyeZ, min: -10, max: 20});
  webglLessonsUI.setupSlider("#innerLimit", {value: radToDeg(innerLimit), slide: updateInnerLimit, min: 0, max: 180});
  webglLessonsUI.setupSlider("#outerLimit", {value: radToDeg(outerLimit), slide: updateOuterLimit, min: 0, max: 180});
  webglLessonsUI.setupSlider("#shiness", {value: shiness, slide: updateShiness, min: 0, max: 500});

  function updateRotation(event, ui) {
    cameraAngleRadians = ui.value;
    drawScene();
  }

  function updatelightX(event, ui) {
    lightX = ui.value;
    drawScene();
  }

  function updatelightY(event, ui) {
    lightY = ui.value;
    drawScene();
  }

  function updatelightZ(event, ui) {
    lightZ = ui.value;
    drawScene();
  }

  function updateEyeX(event, ui) {
    eyeX = ui.value;
    drawScene();
  }

  function updateEyeY(event, ui) {
    eyeY = ui.value;
    drawScene();
  }

  function updateEyeZ(event, ui) {
    eyeZ = ui.value;
    drawScene();
  }

  function updateInnerLimit(event, ui) {
    innerLimit = degToRad(ui.value);
    drawScene();
  }

  function updateOuterLimit(event, ui) {
    outerLimit = degToRad(ui.value);
    drawScene();
  }

  function updateShiness(event, ui) {
    shiness = ui.value;
    drawScene();
  }

  // Compute the projection matrix
  var aspect = 1;
  var zNear = 1;
  var zFar = 2000;
 
  var cameraMatrix = new Matrix4(); 
  var projectionMatrix = new Matrix4();    // Model view projection matrix
  var normalMatrix = new Matrix4(); // Transformation matrix for normals
  //设置环境光颜色
  gl.uniform3f(u_AmbientLight, 0.5, 0.5, 0.5);
  // 设置光照颜色
  gl.uniform3f(lightColor, 1, 1, 1); 
  // 设置高光颜色
  gl.uniform3f(specularColorLocation, 1, 1, 1);

  var drawScene = function() {
    gl.useProgram(program);
    gl.program = program;
    var n = initVertexBuffers(gl);
    if (n < 0) {
      console.log('Failed to set the vertex information');
      return;
    }
    cameraMatrix.setRotate(cameraAngleRadians, 0, 1, 0);
    //设置光源位置
    gl.uniform3f(u_lightWorldPosition, lightX, lightY, lightZ);
    // 设置亮度
    gl.uniform1f(shininessLocation, shiness);
    gl.uniform3fv(lightDirectionLocation, lightDirection);
    gl.uniform1f(u_innerLimit, Math.cos(innerLimit));
    gl.uniform1f(u_outerLimit, Math.cos(outerLimit));
    // Calculate the view projection matrix
    projectionMatrix.setPerspective(100, aspect, zNear, zFar);
    projectionMatrix.lookAt(eyeX, eyeY, eyeZ, 0, 2, 0, 0, 1, 0);
    projectionMatrix.multiply(cameraMatrix);
    // Calculate the matrix to transform the normal based on the model matrix
    normalMatrix.setInverseOf(cameraMatrix);
    normalMatrix.transpose();
    // Pass the model matrix to u_world
    gl.uniformMatrix4fv(u_world, false, cameraMatrix.elements);
    // Pass the model view projection matrix to u_worldViewProjection
    gl.uniformMatrix4fv(u_worldViewProjection, false, projectionMatrix.elements);
    // Pass the transformation matrix for normals to u_worldInverseTranspose
    gl.uniformMatrix4fv(u_worldInverseTranspose, false, normalMatrix.elements);
  
    var texture = gl.createTexture();
    var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');

    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, texture);// 绑定纹理对象到激活的纹理单元
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);// 纹理放大方式
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);// 纹理缩小方式
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);// 纹理水平填充方式
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);// 纹理垂直填充方式
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
    gl.uniform1i(u_Sampler, 0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);

    var v = new Float32Array([
      0.25, 0.25, 0.25,  -0.25, 0.25, 0.25,  -0.25,-0.25, 0.25,   0.25,-0.25, 0.25, // v0-v1-v2-v3 front
      0.25, 0.25, 0.25,   0.25,-0.25, 0.25,   0.25,-0.25,-0.25,   0.25, 0.25,-0.25, // v0-v3-v4-v5 right
      0.25, 0.25, 0.25,   0.25, 0.25,-0.25,  -0.25, 0.25,-0.25,  -0.25, 0.25, 0.25, // v0-v5-v6-v1 up
      -0.25, 0.25, 0.25,  -0.25, 0.25,-0.25,  -0.25,-0.25,-0.25,  -0.25,-0.25, 0.25, // v1-v6-v7-v2 left
      -0.25,-0.25,-0.25,   0.25,-0.25,-0.25,   0.25,-0.25, 0.25,  -0.25,-0.25, 0.25, // v7-v4-v3-v2 down
      0.25,-0.25,-0.25,  -0.25,-0.25,-0.25,  -0.25, 0.25,-0.25,   0.25, 0.25,-0.25  // v4-v7-v6-v5 back
    ]);
    gl.useProgram(lightProgram);
    gl.program = lightProgram;
    if (!initArrayBuffer(gl, "a_Position", v, 3)) return -1;
    // Get the storage locations of uniform variables and so on
    var u_MvpMatrix = gl.getUniformLocation(gl.program, "u_MvpMatrix");
    var modelMatrix = new Matrix4();
    // Calculate the model matrix
    modelMatrix = modelMatrix.setTranslate(lightX, lightY, lightZ)
    // Calculate the view projection matrix
    var mvpMatrix = new Matrix4(); // Model view projection matrix
    mvpMatrix.setPerspective(100, aspect, zNear, zFar);
    mvpMatrix.lookAt(eyeX, eyeY, eyeZ, 0, 2, 0, 0, 1, 0);
    mvpMatrix.multiply(modelMatrix);
    // Pass the model view projection matrix to the variable u_MvpMatrix
    gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
    gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);

    var tCoords = new Float32Array([
      1.0, 0.0, 
      1.0, 1.0, 
      0.0, 1.0, 
      0.0, 0.0,
    ]);
    var positions = new Float32Array([
      10, -2, 10,
      10, -2,-10,
      -10, -2,-10,
      -10, -2, 10,
    ])
    gl.useProgram(landProgram);
    gl.program = landProgram;
    if (!initArrayBuffer(gl, "a_Position", positions, 3)) return -1;
    if (!initArrayBuffer(gl, 'a_TexCoord', tCoords, 2)) return -1;
    var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
    gl.uniform1i(u_Sampler, 0);
    var u_MvpMatrix = gl.getUniformLocation(gl.program, "u_MvpMatrix");
    // var modelMatrix = new Matrix4();
    // Calculate the model matrix
    // modelMatrix = modelMatrix.setTranslate(0, 0, 0)
    // Calculate the view projection matrix
    var mvpMatrix = new Matrix4(); // Model view projection matrix
    mvpMatrix.setPerspective(100, aspect, zNear, zFar);
    mvpMatrix.lookAt(eyeX, eyeY, eyeZ, 0, 2, 0, 0, 1, 0);
    // mvpMatrix.multiply(modelMatrix);
    // Pass the model view projection matrix to the variable u_MvpMatrix
    gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_BYTE, 0);
  };
  drawScene();
}

function initVertexBuffers(gl) {
  // Create a cube
  //    v6----- v5
  //   /|      /|
  //  v1------v0|
  //  | |     | |
  //  | |v7---|-|v4
  //  |/      |/
  //  v2------v3
  // Coordinates
  var vertices = new Float32Array([
     2.0, 2.0, 2.0,  -2.0, 2.0, 2.0,  -2.0,-2.0, 2.0,   2.0,-2.0, 2.0, // v0-v1-v2-v3 front
     2.0, 2.0, 2.0,   2.0,-2.0, 2.0,   2.0,-2.0,-2.0,   2.0, 2.0,-2.0, // v0-v3-v4-v5 right
     2.0, 2.0, 2.0,   2.0, 2.0,-2.0,  -2.0, 2.0,-2.0,  -2.0, 2.0, 2.0, // v0-v5-v6-v1 up
    -2.0, 2.0, 2.0,  -2.0, 2.0,-2.0,  -2.0,-2.0,-2.0,  -2.0,-2.0, 2.0, // v1-v6-v7-v2 left
    -2.0,-2.0,-2.0,   2.0,-2.0,-2.0,   2.0,-2.0, 2.0,  -2.0,-2.0, 2.0, // v7-v4-v3-v2 down
     2.0,-2.0,-2.0,  -2.0,-2.0,-2.0,  -2.0, 2.0,-2.0,   2.0, 2.0,-2.0  // v4-v7-v6-v5 back
  ]);

  var texCoords = new Float32Array([
    1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
    0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0,
    1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0,
    1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
    0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
    0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0
  ]);

  // Normal
  var normals = new Float32Array([
    0.0, 0.0, 1.0,   0.0, 0.0, 1.0,   0.0, 0.0, 1.0,   0.0, 0.0, 1.0,  // v0-v1-v2-v3 front
    1.0, 0.0, 0.0,   1.0, 0.0, 0.0,   1.0, 0.0, 0.0,   1.0, 0.0, 0.0,  // v0-v3-v4-v5 right
    0.0, 1.0, 0.0,   0.0, 1.0, 0.0,   0.0, 1.0, 0.0,   0.0, 1.0, 0.0,  // v0-v5-v6-v1 up
   -1.0, 0.0, 0.0,  -1.0, 0.0, 0.0,  -1.0, 0.0, 0.0,  -1.0, 0.0, 0.0,  // v1-v6-v7-v2 left
    0.0,-1.0, 0.0,   0.0,-1.0, 0.0,   0.0,-1.0, 0.0,   0.0,-1.0, 0.0,  // v7-v4-v3-v2 down
    0.0, 0.0,-1.0,   0.0, 0.0,-1.0,   0.0, 0.0,-1.0,   0.0, 0.0,-1.0   // v4-v7-v6-v5 back
  ]);

  // Indices of the vertices
  var indices = new Uint8Array([
    0, 1, 2,   0, 2, 3,     // front
    4, 5, 6,   4, 6, 7,     // right
    8, 9,10,   8,10,11,     // up
    12,13,14,  12,14,15,    // left
    16,17,18,  16,18,19,    // down
    20,21,22,  20,22,23     // back
  ]);

  // Write the vertex property to buffers (coordinates, colors and normals)
  if (!initArrayBuffer(gl, 'a_position', vertices, 3)) return -1;
  if (!initArrayBuffer(gl, 'a_normal', normals, 3)) return -1;
  if (!initArrayBuffer(gl, 'a_TexCoord', texCoords, 2)) return -1;
  // Unbind the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  // Write the indices to the buffer object
  var indexBuffer = gl.createBuffer();
  if (!indexBuffer) {
    console.log('Failed to create the buffer object');
    return false;
  }
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

  return indices.length;
}

function initArrayBuffer(gl, attribute, data, num) {
  // Create a buffer object
  var buffer = gl.createBuffer();
  if (!buffer) {
    console.log('Failed to create the buffer object');
    return false;
  }
  // Write date into the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  // Assign the buffer object to the attribute variable
  var a_attribute = gl.getAttribLocation(gl.program, attribute);
  if (a_attribute < 0) {
    console.log('Failed to get the storage location of ' + attribute);
    return false;
  }
  gl.vertexAttribPointer(a_attribute, num, gl.FLOAT, false, 0, 0);
  // Enable the assignment of the buffer object to the attribute variable
  gl.enableVertexAttribArray(a_attribute);

  return true;
}

function degToRad(degrees)
{
  var pi = Math.PI;
  return degrees * (pi/180);
}

function radToDeg(r) {
  return r * 180 / Math.PI;
}
